package com.fks.fks_service.controller;

import com.fks.fks_service.mapper.AddressMapper;
import com.fks.fks_service.base.JsonResult;
import com.fks.fks_service.base.ResultCode;
import com.fks.fks_service.pojo.AddressDB;
import com.fks.fks_service.utils.DateUtils;
import com.fks.fks_service.utils.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api")
@Transactional//开启事务回滚
@Api(tags = "收获地址模块")
public class AddressController {


    @Autowired
    AddressMapper addressMapper;

    /**
     * 获取收获地址
     * @param request token
     * @return list
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header")
    })
    @ApiOperation(value = "获取收获地址", notes = "获取用户收获地址")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = AddressDB.class)
    })
    @PostMapping("/getAddress")
    public JsonResult getAddress(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //获取收获地址信息
        List<AddressDB> addressDBList = addressMapper.getAddressByUserId(userId);
        if (addressDBList.size()==0){
            return JsonResult.error(2000,"没有地址");
        }
        return JsonResult.success("获取收获地址成功").data(addressDBList);
    }

    /**
     *
     * 修改收获地址
     * @param request token
     * addressId要修改的收获地址id  address地址信息
     * phone收货人电话  consigneeName收货人姓名  isDefault是否为默认地址
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "addressId",value = "要修改的收获地址id",required = true,paramType = "param"),
            @ApiImplicitParam(name = "address",value = "地址信息",required = true,paramType = "param"),
            @ApiImplicitParam(name = "phone",value = "收货人电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "consigneeName",value = "收货人姓名",required = true,paramType = "param"),
            @ApiImplicitParam(name = "isDefault",value = "是否为默认地址",required = true,paramType = "param"),
            @ApiImplicitParam(name = "longitude",value = "经度",required = true,paramType = "param"),
            @ApiImplicitParam(name = "latitude",value = "纬度",required = true,paramType = "param"),
    })
    @ApiOperation(value = "修改收获地址", notes = "修改用户收获地址")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/updateAddress")
    public JsonResult updateAddress(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //获取新的收获地址信息
        String addressId = request.getParameter("addressId");
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String consigneeName = request.getParameter("consigneeName");
        String isDefault = request.getParameter("isDefault");
        String longitude = request.getParameter("longitude");
        String latitude = request.getParameter("latitude");
        //校验参数
        if (addressId==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (address==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (phone==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (consigneeName==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (isDefault==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (longitude==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (latitude==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        if ("1".equals(isDefault)){
            List<AddressDB> addressByUserId = addressMapper.getAddressByUserId(userId);
            for (AddressDB addressDB : addressByUserId) {
                addressDB.setIsDefault("0");
                addressMapper.updateAddress(addressDB);
            }
        }
        AddressDB addressDB = new AddressDB();
        addressDB.setId(Integer.parseInt(addressId));
        addressDB.setAddress(address);
        addressDB.setPhone(phone);
        addressDB.setConsigneeName(consigneeName);
        addressDB.setIsDefault(isDefault);
        addressDB.setUpdateTime(DateUtils.getNowTime());
        addressDB.setLongitude(longitude);
        addressDB.setLatitude(latitude);
        //修改
        addressMapper.updateAddress(addressDB);
        return JsonResult.success("修改收货地址成功");
    }

    /**
     * 删除收获地址
     * @param request token addressId要删除的收获地址的id
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "addressId",value = "要删除的收获地址的id",required = true,paramType = "param")
    })
    @ApiOperation(value = "删除收获地址", notes = "删除收获地址")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/deleteAddress")
    public JsonResult deleteAddress(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取要删除的收获地址id
        String addressId = request.getParameter("addressId");
        if (addressId==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        addressMapper.deleteAddress(addressId);
        return JsonResult.success("删除收获地址成功");
    }

    /**
     * 新增收获地址
     * @param request token
     * address地址信息  phone收货人电话
     * consigneeName收货人姓名  isDefault是否为默认地址
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "address",value = "地址信息",required = true,paramType = "param"),
            @ApiImplicitParam(name = "phone",value = "收货人电话",required = true,paramType = "param"),
            @ApiImplicitParam(name = "consigneeName",value = "收货人姓名",required = true,paramType = "param"),
            @ApiImplicitParam(name = "isDefault",value = "是否为默认地址（0不是默认地址，1是默认地址）",required = true,paramType = "param"),
            @ApiImplicitParam(name = "area",value = "归属地区,省份,市,区,英文逗号隔开",required = true,paramType = "param"),
    })
    @ApiOperation(value = "新增收获地址", notes = "新增收获地址")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/addAddress")
    public JsonResult addAddress(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //获取新的收获地址信息
        String address = request.getParameter("address");
        String phone = request.getParameter("phone");
        String consigneeName = request.getParameter("consigneeName");
        String isDefault = request.getParameter("isDefault");
        String area = request.getParameter("area");
        //校验参数
        if (address==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (phone==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (consigneeName==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (isDefault==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }else if (area==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        if ("1".equals(isDefault)){
            List<AddressDB> addressByUserId = addressMapper.getAddressByUserId(userId);
            for (AddressDB addressDB : addressByUserId) {
                addressDB.setIsDefault("0");
                addressMapper.updateAddress(addressDB);
            }
        }
        //提取省份,市,区
        String[] split = area.split(",");
        String province = "";
        String city = "";
        if (split.length==1){
        }else if (split.length==2){
            province = split[0];
            city = split[1];
        }else if (split.length==3){
            province = split[0];
            city = split[1];
            area = split[2];
        }
        AddressDB addressDB = new AddressDB();
        addressDB.setUid(userId);
        addressDB.setAddress(address);
        addressDB.setPhone(phone);
        addressDB.setConsigneeName(consigneeName);
        addressDB.setIsDefault(isDefault);
        addressDB.setCreateTime(DateUtils.getNowTime());
        addressDB.setProvince(province);
        addressDB.setCity(city);
        addressDB.setArea(area);
        addressMapper.insertAddress(addressDB);
        return JsonResult.success("新增收获地址成功");
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "id",value = "地址id",required = true,paramType = "param"),
    })
    @ApiOperation(value = "获取收货地址详情", notes = "新增收货地址详情")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/getAddressInformation")
    public JsonResult getAddressInformation(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        String id = request.getParameter("id");
        //校验参数
        if (id==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        AddressDB address = addressMapper.getAddressById(Integer.parseInt(id));
        return JsonResult.success("获取地址详情成功").data(address);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "token",value = "认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "jwtRefreshToken",value = "是否重置认证令牌",required = true,paramType = "header"),
            @ApiImplicitParam(name = "addressId",value = "要设为默认的收获地址id",required = true,paramType = "param"),
    })
    @ApiOperation(value = "修改默认收货地址", notes = "修改默认收货地址")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "成功", response = String.class)
    })
    @PostMapping("/updateDefault")
    public JsonResult updateDefault(HttpServletRequest request){
        String token = request.getHeader("token");
        if (token==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        //获取用户id
        Claims tokenClaims = JwtTokenUtil.getClaims(token);
        int userId = Integer.parseInt(String.valueOf(tokenClaims.get("userId")));
        //获取新的收获地址信息
        String addressId = request.getParameter("addressId");
        //校验参数
        if (addressId==null){
            return JsonResult.error(ResultCode.param_is_null,"缺少参数");
        }
        List<AddressDB> addressByUserId = addressMapper.getAddressByUserId(userId);
        for (AddressDB addressDB : addressByUserId) {
            addressDB.setIsDefault("0");
            addressMapper.updateAddress(addressDB);
        }

        AddressDB addressDB = new AddressDB();
        addressDB.setId(Integer.parseInt(addressId));
        addressDB.setUpdateTime(DateUtils.getNowTime());
        //修改
        addressMapper.updateDefault(addressDB);
        return JsonResult.success("修改默认收货地址成功");
    }


}
